package beans;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.Startup;
import javax.jms.JMSException;
import javax.jms.MessageListener;

import beans.interfaces.AgentDataLocal;
import beans.interfaces.ClientJMSListenerLocal;
import beans.interfaces.TaskManagerLocal;
import model.ACLMessage;
import model.AgentInfo;
import util.MessageDecryptor;

/**
 * Session Bean implementation class MessageManager
 */
@Startup
@MessageDriven(activationConfig = { 
        @ActivationConfigProperty(propertyName = "destinationType", 
                propertyValue = "javax.jms.Topic"),
        @ActivationConfigProperty(propertyName="destination",
                propertyValue="topic/mojTopic2")                
        })
public class MessageManager implements MessageListener {

	@EJB
	private AgentDataLocal agentData;
	
	@EJB
	private TaskManagerLocal tm;
	
	@EJB
	private ConnectionManagerLocal cm;
	
	@EJB
	private ClientJMSListenerLocal facilitator;
    /**
     * Default constructor. 
     */
    public MessageManager() {
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public void onMessage(javax.jms.Message message) {
    	ACLMessage aclMessage=null;
		try {
			aclMessage = MessageDecryptor.decryptACLMessage(message);
		}
		catch(ClassCastException cce) {
			return;
		} 
		catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	if(aclMessage!=null) {
	    	AgentInfo reciever = aclMessage.getReciever();
	    	
	    	if(reciever==null) {
	    		tm.executeOnAgents(aclMessage);
	    		if(agentData.getLocalHost().equals(aclMessage.getSender().getLocalHost())) {
	    			cm.sendToOtherServer(aclMessage);
	    		}
	    	} else {
	    		if(reciever.getLocalHost().equals(agentData.getLocalHost())) {
	    			tm.executeOnAgents(aclMessage);
	    			//deo za reply klijentu
	    			String protocol = aclMessage.getProtocol();
	    	    	if(protocol!=null) {
	    				if(protocol.contains("tender done")) {
	    					facilitator.sendTenderResultToClient(aclMessage);
	    				}
	    	    	}
	    		}
	    		else {
	    			cm.sendToOtherServer(aclMessage);
	    		}
	    	}
    	}
    }

}
